﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Linq;
using VO.Entities;

namespace VO.Business.Controllers
{
    public static class TracksDonesController
    {
        public static List<TrackDone> GetTracksDones()
        {
            using (ModelVOContainer ctx = new ModelVOContainer())
            {
                List<TrackDone> list = ctx.TrackDones.OrderBy(t => t.PostedDate).ToList();
                list.Reverse();
                return list;
            }
        }

        public static List<TrackDone> GetUserTracksDones(int userId)
        {
            using (ModelVOContainer ctx = new ModelVOContainer())
            {
                List<TrackDone> list = ctx.TrackDones.Include("Track.TrackCategory").Where(p => p.UserId == userId).OrderBy(t => t.PostedDate).ToList();
                list.Reverse();
                return list;
            }
        }

        public static TrackDone GetTrackDone(Guid id)
        {
            using (ModelVOContainer ctx = new ModelVOContainer())
            {
                return ctx.TrackDones.SingleOrDefault(p => p.Id == id);
            }
        }

        public static bool SaveTrackDone(TrackDone trackDone, bool isnew)
        {
            using (ModelVOContainer ctx = new ModelVOContainer())
            {
                try
                {
                    if (isnew)
                    {
                        ctx.TrackDones.Attach(trackDone);
                        ctx.ObjectStateManager.ChangeObjectState(trackDone, EntityState.Added);

                        Track trToUpdate = ctx.Tracks.Where(t => t.Id == trackDone.TrackId).SingleOrDefault();
                        trToUpdate.Locked = true;

                        return ctx.SaveChanges() > 0;
                    }
                    else
                    {
                        ctx.TrackDones.Attach(trackDone);
                        ctx.ObjectStateManager.ChangeObjectState(trackDone, EntityState.Modified);

                        return ctx.SaveChanges() > 0;
                    }

                }
                catch (OptimisticConcurrencyException exOpt)
                {
                    ctx.Refresh(RefreshMode.ClientWins, trackDone);

                    return ctx.SaveChanges() > 0;
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
    }
}
